<template>
    <div class="common-layout">
        <el-container>
            <el-main style="padding-bottom: 80px;">
                <el-form ref="stockinFormRef" :model="stockinForm" :rules="rules" label-width="120px"
                    :disabled="isDetailMode">
                    <el-card class="card-block">
                        <template #header>
                            <span class="card-title">基础信息</span>
                        </template>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="进货单号" prop="stockinGoodsNo">
                                    <el-input v-model="stockinForm.stockinGoodsNo" placeholder="自动获取系统编号" readonly />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="进货日期" prop="stockinGoodsDate">
                                    <el-date-picker v-model="stockinForm.stockinGoodsDate" type="date"
                                        value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="供应商" prop="supplierId">
                                    <div class="inline-input">
                                        <el-select v-model="stockinForm.supplierId" placeholder="请选择" filterable
                                            clearable style="flex: 1">
                                            <el-option v-for="item in supplierOptions" :key="item.supplierId"
                                                :label="item.supplierName" :value="String(item.supplierId)" />
                                        </el-select>
                                        <el-button type="text" class="link-btn"
                                            @click="gotoCreateSupplier">设置</el-button>
                                    </div>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="联系人">
                                    <el-input v-model="stockinForm.stockinContact" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="联系方式">
                                    <el-input v-model="stockinForm.stockinContactPhone" placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="进货部门" prop="organizationId">
                                    <el-input v-model="stockinForm.organizationName" placeholder="请选择" readonly
                                        @click="openOrgDialog">
                                        <template #suffix>
                                            <el-button v-if="stockinForm.organizationId" text
                                                @click.stop="clearOrgSelection">
                                                <el-icon>
                                                    <Close />
                                                </el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openOrgDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="12">
                                <el-form-item label="进货人" prop="userId">
                                    <el-input v-model="stockinForm.userName" placeholder="请选择" readonly
                                        @click="openUserDialog">
                                        <template #suffix>
                                            <el-button v-if="stockinForm.userId" text @click.stop="clearUserSelection">
                                                <el-icon>
                                                    <Close />
                                                </el-icon>
                                            </el-button>
                                            <el-button text @click.stop="openUserDialog">···</el-button>
                                        </template>
                                    </el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row :gutter="20">
                            <el-col :span="24">
                                <el-form-item label="备注">
                                    <el-input v-model="stockinForm.remark" type="textarea" :rows="3"
                                        placeholder="请输入" />
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-card>

                    <el-card class="card-block">
                        <template #header>
                            <div class="detail-header">
                                <span class="card-title">进货明细</span>
                                <div class="detail-actions" v-if="isEditMode">
                                    <el-button type="primary" @click="openProductDialog">新增</el-button>
                                    <el-button type="danger" plain :disabled="!selectedDetailRows.length"
                                        @click="removeSelectedDetails">
                                        移除
                                    </el-button>
                                </div>
                            </div>
                        </template>
                        <el-table ref="detailTableRef" :data="stockinDetails" border style="width: 100%"
                            highlight-current-row @selection-change="handleDetailSelectionChange"
                            :empty-text="isEditMode ? '请先通过“新增”按钮选择货品' : '暂无进货明细'">
                            <el-table-column v-if="isEditMode" type="selection" width="50" />
                            <el-table-column type="index" label="序号" width="60" />
                            <el-table-column prop="productName" label="货品名称" min-width="160" />
                            <el-table-column prop="productCode" label="货品编号" min-width="140" />
                            <el-table-column label="规格" min-width="160">
                                <template #default="{ row }">
                                    {{
                                        row.productUnit ||
                                        row.specification ||
                                        '--'
                                    }}
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" min-width="120">
                                <template #default="{ row }">
                                    <el-select v-model="row.unit" placeholder="请选择" style="width: 140px" filterable
                                        clearable @change="handleUnitChange(row)">
                                        <!-- 如果有货品自带的单位组，优先显示（带分组） -->
                                        <template v-if="row.unitGroups && row.unitGroups.length > 0">
                                            <template v-for="group in row.unitGroups" :key="group.label">
                                                <el-option-group :label="group.label">
                                                    <el-option v-for="option in group.options"
                                                        :key="`group-${option.value}`" :label="option.label"
                                                        :value="option.value">
                                                        <span>{{ option.label }}</span>
                                                        <span v-if="option.description" class="unit-desc">
                                                            {{ option.description }}
                                                        </span>
                                                    </el-option>
                                                </el-option-group>
                                            </template>
                                        </template>
                                        <!-- 显示所有可用单位（从API获取） -->
                                        <el-option-group v-if="unitOptions.length > 0" label="所有单位">
                                            <el-option v-for="unit in unitOptions" :key="unit.unitId"
                                                :label="unit.unitName" :value="unit.unitName">
                                                {{ unit.unitName }}
                                            </el-option>
                                        </el-option-group>
                                        <!-- 如果没有从API获取到单位，使用默认单位 -->
                                        <template v-if="unitOptions.length === 0">
                                            <el-option v-for="(unit, index) in DEFAULT_UNIT_OPTIONS" :key="index"
                                                :label="unit" :value="unit">
                                                {{ unit }}
                                            </el-option>
                                        </template>
                                    </el-select>
                                </template>
                            </el-table-column>
                            <el-table-column prop="productTypeName" label="货品类型" min-width="120" />
                            <el-table-column prop="currentStock" label="当前库存" width="100" />
                            <el-table-column label="* 进货数量" width="130">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.quantity" :min="1" :precision="0"
                                        controls-position="right" placeholder="必填" :value-on-clear="1"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="* 进货单价" width="140">
                                <template #default="{ row }">
                                    <el-input-number v-model="row.unitPrice" :min="0.01" :precision="2"
                                        controls-position="right" placeholder="必填" :value-on-clear="0.01"
                                        @change="updateDetailAmount(row)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="金额" width="120">
                                <template #default="{ row }">
                                    ¥{{ row.amount?.toFixed(2) || '0.00' }}
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" min-width="160">
                                <template #default="{ row }">
                                    <el-input v-model="row.remark" placeholder="可填写补充说明" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="80" fixed="right">
                                <template #default="scope">
                                    <el-button link type="danger" size="small" @click="removeDetail(scope.$index)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <div class="detail-summary" v-if="stockinDetails.length">
                            <span>货品种类：{{ totalProductKinds }}</span>
                            <span>货品数量：{{ totalProductQuantity }}</span>
                            <span>总金额：¥{{ totalProductAmount.toFixed(2) }}</span>
                        </div>
                    </el-card>
                </el-form>
            </el-main>
        </el-container>

        <el-dialog v-model="orgDialogVisible" title="选择部门" width="480px">
            <el-input v-model="orgSearchText" placeholder="搜索部门名称" clearable class="dialog-search" />
            <el-tree :data="filteredOrgTree" node-key="organizationId" :props="orgTreeProps" highlight-current
                default-expand-all @node-click="handleSelectOrg" style="max-height: 360px; overflow: auto;" />
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="orgDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmOrg">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="userDialogVisible" title="选择人员" width="480px">
            <el-input v-model="userSearchText" placeholder="搜索人员名称" clearable class="dialog-search" />
            <el-table :data="filteredUserList" height="360" border @row-click="handleSelectUser"
                style="cursor: pointer;">
                <el-table-column prop="userName" label="姓名" />
                <el-table-column prop="organizationName" label="部门" />
            </el-table>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="userDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmUser">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="productDialogVisible" title="添加货品" width="900px">
            <el-form :inline="true" :model="productSearchForm" class="product-search-form">
                <el-form-item>
                    <el-input v-model="productSearchForm.keyword" placeholder="请输入货品编号/名称" clearable />
                </el-form-item>
                <el-form-item>
                    <el-select v-model="productSearchForm.unit" placeholder="请选择单位" clearable filterable>
                        <el-option v-for="option in productUnitOptions" :key="option" :label="option" :value="option" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="resetProductSearch">重置</el-button>
                    <el-button type="primary" @click="searchProducts">查询</el-button>
                </el-form-item>
            </el-form>

            <el-table :data="productList" border height="420" v-loading="productTableLoading"
                @selection-change="handleProductSelectionChange">
                <el-table-column type="selection" width="50" />
                <el-table-column type="index" label="序号" width="60" />
                <el-table-column prop="productCode" label="货品编号" min-width="140" />
                <el-table-column prop="productName" label="货品名称" min-width="160" />
                <el-table-column prop="producttypeName" label="货品类型" min-width="120" />
                <el-table-column label="规格" min-width="120">
                    <template #default="{ row }">
                        {{ row.productUnit || row.mainUnit || row.unitDisplay || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="单位" min-width="120">
                    <template #default="{ row }">
                        {{ row.productspecification || row.productSpecification || row.specification || '--' }}
                    </template>
                </el-table-column>
                <el-table-column prop="productInmoney" label="入库单价" min-width="100" />
                <el-table-column prop="inventoryCurrtnumber" label="当前库存" min-width="100" />
            </el-table>

            <div class="product-pagination">
                <el-pagination v-model:current-page="productPagination.pageindex"
                    v-model:page-size="productPagination.pagesize" :page-sizes="[10, 20, 50]"
                    layout="total, sizes, prev, pager, next" :total="productPagination.total"
                    @size-change="handleProductSizeChange" @current-change="handleProductCurrentChange" />
            </div>
            <template #footer>
                <div style="text-align: right;">
                    <el-button @click="productDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="confirmProductSelection">确定</el-button>
                </div>
            </template>
        </el-dialog>

        <div class="fixed-footer">
            <div class="footer-content">
                <el-button @click="goBack">关闭</el-button>
                <el-button v-if="isEditMode" @click="resetForm">重置</el-button>
                <el-button v-if="isEditMode" type="primary" :loading="saving" @click="handleSave">保存修改</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { computed, nextTick, onMounted, reactive, ref } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, type FormInstance } from 'element-plus'
import { Close } from '@element-plus/icons-vue'
import myaxios from '@/http/MyAxios'

const router = useRouter()
const route = useRoute()

const stockinFormRef = ref<FormInstance>()

const stockinForm = reactive({
    stockinGoodsNo: '',
    stockinGoodsDate: '',
    supplierId: '',
    supplierName: '',
    stockinContact: '',
    stockinContactPhone: '',
    organizationId: '',
    organizationName: '',
    userId: '',
    userName: '',
    remark: '',
})

const isDetailMode = computed(
    () => route.name === 'DetailStockingGoods' || route.query.mode === 'detail',
)
const isEditMode = computed(() => !isDetailMode.value)
const detailLoading = ref(false)
const currentStockinGoodsId = ref<string | number | null>(null)

const rules = {
    stockinGoodsNo: [{ required: true, message: '进货单号不能为空', trigger: 'blur' }],
    stockinGoodsDate: [{ required: true, message: '请选择进货日期', trigger: 'change' }],
    supplierId: [{ required: true, message: '请选择供应商', trigger: 'change' }],
    organizationId: [{ required: true, message: '请选择进货部门', trigger: 'change' }],
    userId: [{ required: true, message: '请选择进货人', trigger: 'change' }],
}

interface SupplierItem {
    supplierId: string | number
    supplierName: string
}

interface OrganizationItem {
    organizationId: string | number
    organizationParentId?: string | number | null
    organizationName: string
    children?: OrganizationItem[]
}

interface UserItem {
    userId: string | number
    userName: string
    organizationId?: string | number
    organizationName?: string
}

interface UnitOption {
    label: string
    value: string
    description?: string
}

interface UnitOptionGroup {
    label: string
    options: UnitOption[]
}

interface StockinDetailItem {
    lineId: string
    stockinGoodsDetailId?: string | number | null
    productId: string | number
    productName: string
    productCode: string
    specification?: string
    productSpecification?: string
    productUnit?: string
    unit: string
    unitGroups: UnitOptionGroup[]
    productTypeName?: string
    currentStock?: number
    currentInventory?: number
    quantity: number | null | undefined // 允许null或undefined，因为el-input-number初始值可能是null
    unitPrice: number
    amount: number
    remark: string
}

interface ProductListItem {
    productId: string | number
    productCode: string
    productName: string
    producttypeName?: string
    productSpecification?: string
    productspecification?: string
    specification?: string
    productUnit?: string
    inventoryCurrtnumber?: number
    productInmoney?: number
    unitDisplay?: string
    mainUnit?: string
    [key: string]: any
}

const supplierOptions = ref<SupplierItem[]>([])
let supplierLoadPromise: Promise<void> | null = null
const STOCKIN_EDIT_CACHE_KEY = 'STOCKIN_EDIT_CACHE'
const normalizeSupplierItem = (item: any): SupplierItem => ({
    supplierId: String(
        item?.supplierId ??
        item?.SupplierId ??
        item?.id ??
        item?.value ??
        '',
    ),
    supplierName: item?.supplierName ?? item?.SupplierName ?? item?.label ?? item?.name ?? '',
})

const orgDialogVisible = ref(false)
const orgTreeData = ref<OrganizationItem[]>([])
const orgNameMap = ref<Record<string, string>>({})
const orgSearchText = ref('')
const selectedOrgNode = ref<OrganizationItem | null>(null)
let orgLoadPromise: Promise<void> | null = null

const orgTreeProps = {
    children: 'children',
    label: 'organizationName',
}

const userDialogVisible = ref(false)
const userList = ref<UserItem[]>([])
const userSearchText = ref('')
const selectedUser = ref<UserItem | null>(null)
let userLoadPromise: Promise<void> | null = null

const stockinDetails = ref<StockinDetailItem[]>([])
const selectedDetailRows = ref<StockinDetailItem[]>([])
const saving = ref(false)

const productDialogVisible = ref(false)
const productTableLoading = ref(false)
const productList = ref<ProductListItem[]>([])
const selectedProducts = ref<ProductListItem[]>([])
const DEFAULT_UNIT_OPTIONS = ['箱', '个', '套', '台', '条', '包', '瓶', '袋', '件']
const productUnitOptions = ref<string[]>([])

// 单位列表（从API获取）
interface UnitItem {
    unitId: string | number
    unitCode: string
    unitName: string
    unitState?: number
}
const unitOptions = ref<UnitItem[]>([])
let unitLoadPromise: Promise<void> | null = null

const productSearchForm = reactive({
    keyword: '',
    unit: '',
})

const productPagination = reactive({
    pageindex: 1,
    pagesize: 10,
    total: 0,
})

const loadSuppliers = async () => {
    if (!supplierLoadPromise) {
        supplierLoadPromise = (async () => {
            try {
                const res = await myaxios.get('/api/StockinGoods/GetSuppliersForStockin')
                if (res.data.code === 200) {
                    supplierOptions.value = (res.data.data || []).map(normalizeSupplierItem)
                }
            } catch (error) {
                console.error('获取供应商失败:', error)
            }
        })()
    }
    await supplierLoadPromise
}

// 加载单位列表
const loadUnitOptions = async () => {
    if (!unitLoadPromise) {
        unitLoadPromise = (async () => {
            try {
                const res = await myaxios.get('/api/Unit/GetUnitList')
                if (res.data.code === 200 || res.data.success) {
                    const units = res.data.data || []
                    // 只获取启用状态的单位
                    unitOptions.value = units
                        .filter((unit: any) => unit.unitState === 1 || unit.unitState === undefined)
                        .map((unit: any) => ({
                            unitId: unit.unitId,
                            unitCode: unit.unitCode || '',
                            unitName: unit.unitName || '',
                            unitState: unit.unitState,
                        }))
                }
            } catch (error) {
                console.error('获取单位列表失败:', error)
                // 如果API失败，使用默认单位列表
                unitOptions.value = DEFAULT_UNIT_OPTIONS.map((name, index) => ({
                    unitId: index + 1,
                    unitCode: name,
                    unitName: name,
                    unitState: 1,
                }))
            }
        })()
    }
    await unitLoadPromise
}

const buildOrgNameMap = (nodes: OrganizationItem[]) => {
    const map: Record<string, string> = {}
    const traverse = (list: OrganizationItem[]) => {
        list.forEach((item) => {
            map[String(item.organizationId)] = item.organizationName
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(nodes)
    orgNameMap.value = map
}

const applyOrgNameToUsers = () => {
    if (!userList.value.length) return
    userList.value = userList.value.map((item) => ({
        ...item,
        organizationName:
            item.organizationName ||
            (item.organizationId ? orgNameMap.value[String(item.organizationId)] : '') ||
            '',
    }))
}

const normalizeStockinGoodsId = (value: any): string | number | null => {
    if (value === undefined || value === null) return null
    if (Array.isArray(value)) return normalizeStockinGoodsId(value[0])
    return value as string | number
}

const normalizeOrganizationNodes = (nodes: any[]): OrganizationItem[] => {
    const list: OrganizationItem[] = []
    const traverse = (items: any[]) => {
        items.forEach((item) => {
            const normalized: OrganizationItem = {
                ...item,
                organizationId: item.organizationId ?? item.id ?? item.value,
                organizationName: item.organizationName ?? item.label ?? item.name ?? '',
                organizationParentId:
                    item.organizationParentId ??
                    item.parentId ??
                    item.pid ??
                    item.parent ??
                    null,
                children: [],
            }
            list.push(normalized)
            if (item.children && item.children.length) {
                traverse(item.children)
            }
        })
    }
    traverse(nodes)
    return list
}

const buildOrgTree = (list: OrganizationItem[]): OrganizationItem[] => {
    const nodeMap = new Map<string | number, OrganizationItem>()
    const tree: OrganizationItem[] = []

    list.forEach((item) => {
        const normalized: OrganizationItem = {
            ...item,
            children: item.children ? [...item.children] : [],
        }
        nodeMap.set(normalized.organizationId, normalized)
    })

    nodeMap.forEach((item) => {
        const parentId = item.organizationParentId
        if (parentId && nodeMap.has(parentId)) {
            const parent = nodeMap.get(parentId)!
            parent.children = parent.children || []
            parent.children.push(item)
        } else {
            tree.push(item)
        }
    })

    return tree
}

const loadOrganizations = async () => {
    if (!orgLoadPromise) {
        orgLoadPromise = (async () => {
            try {
                const res = await myaxios.get('api/Supplier/GetOrganization')
                if (res.data.code === 200) {
                    const rawList = res.data.data || []
                    const normalizedList = normalizeOrganizationNodes(rawList)
                    const treeData = buildOrgTree(normalizedList)
                    orgTreeData.value = treeData.length ? treeData : normalizedList
                    buildOrgNameMap(orgTreeData.value)
                    applyOrgNameToUsers()
                }
            } catch (error) {
                console.error('获取部门失败:', error)
            }
        })()
    }
    await orgLoadPromise
}

const loadUsers = async () => {
    if (!userLoadPromise) {
        userLoadPromise = (async () => {
            try {
                const res = await myaxios.get('api/Supplier/GetUser')
                if (res.data.code === 200) {
                    userList.value = (res.data.data || []).map((item: UserItem) => ({
                        ...item,
                        organizationName:
                            item.organizationName ||
                            (item.organizationId ? orgNameMap.value[String(item.organizationId)] : '') ||
                            '',
                    }))
                }
            } catch (error) {
                console.error('获取用户失败:', error)
            }
            applyOrgNameToUsers()
        })()
    }
    await userLoadPromise
}

const formatDateValue = (value: any) => {
    if (!value) return ''
    if (typeof value === 'string') {
        if (value.includes('T')) {
            return value.slice(0, 10)
        }
        return value
    }
    return ''
}

const applyStockinBaseInfo = (info: any) => {
    if (!info) return
    stockinForm.stockinGoodsNo = info.stockinGoodsNo || info.StockinGoodsNo || stockinForm.stockinGoodsNo || ''
    stockinForm.stockinGoodsDate =
        formatDateValue(info.stockinGoodsDate || info.stockinTime || info.StockinGoodsDate) ||
        stockinForm.stockinGoodsDate ||
        ''
    const supplierIdValue = info.supplierId ?? info.SupplierId ?? stockinForm.supplierId ?? ''
    stockinForm.supplierId = String(supplierIdValue || '')
    const supplierNameValue = info.supplierName || info.SupplierName || info.supplier || ''
    if (supplierNameValue) {
        stockinForm.supplierName = supplierNameValue
    }
    const supplierItem = supplierOptions.value.find(
        (item) => String(item.supplierId) === String(supplierIdValue),
    )
    if (!supplierItem && (supplierIdValue || supplierNameValue)) {
        supplierOptions.value.push(
            normalizeSupplierItem({
                supplierId: supplierIdValue || Date.now(),
                supplierName: supplierNameValue || String(supplierIdValue),
            }),
        )
    }
    stockinForm.stockinContact = info.stockinContact || info.contact || stockinForm.stockinContact || ''
    stockinForm.stockinContactPhone =
        info.stockinContactPhone || info.contactPhone || stockinForm.stockinContactPhone || ''
    stockinForm.organizationId = String(info.organizationId ?? info.OrganizationId ?? stockinForm.organizationId ?? '')
    stockinForm.organizationName =
        info.organizationName || info.OrganizationName || info.stockinDepartment || stockinForm.organizationName || ''
    stockinForm.userId = String(info.userId ?? info.UserId ?? stockinForm.userId ?? '')
    stockinForm.userName = info.userName || info.UserName || info.stockinUser || stockinForm.userName || ''
    stockinForm.remark = info.remark || info.stockinRemark || stockinForm.remark || ''
}

const preloadBaseInfoFromCache = () => {
    const cacheText = sessionStorage.getItem(STOCKIN_EDIT_CACHE_KEY)
    if (!cacheText) return
    try {
        const cached = JSON.parse(cacheText)
        applyStockinBaseInfo(cached)
    } catch (error) {
        console.warn('解析缓存的进货单信息失败:', error)
    }
}

const buildUnitGroupsFromSingleUnit = (unit: string): UnitOptionGroup[] => {
    if (!unit) return []
    return [
        {
            label: '当前单位',
            options: [
                {
                    label: unit,
                    value: unit,
                },
            ],
        },
    ]
}

const transformDetailResponse = (detail: any): StockinDetailItem => {
    const productId =
        detail.productId ??
        detail.productID ??
        detail.id ??
        detail.ProductId ??
        ''
    const productName = detail.productName || detail.ProductName || detail.goodsName || ''
    const productCode = detail.productCode || detail.ProductCode || detail.goodsCode || ''
    const specification =
        detail.specificationModel ||
        detail.productSpecification ||
        detail.productUnit ||
        detail.specification ||
        detail.productUnitName ||
        ''
    const unit =
        detail.unitName ||
        detail.unit ||
        detail.productUnit ||
        detail.productSpecification ||
        ''
    const quantity = Number(detail.quantity ?? detail.stockinGoodsCount ?? detail.purchaseCount ?? 0)
    const normalizedQuantity = Number.isFinite(quantity) && !isNaN(quantity) ? quantity : null
    const unitPrice = Number(detail.purchasePrice ?? detail.unitPrice ?? detail.stockinPrice ?? 0)
    const normalizedUnitPrice = Number.isFinite(unitPrice) && !isNaN(unitPrice) ? unitPrice : 0
    let amountValue =
        detail.amount ??
        detail.totalAmount ??
        detail.totalPrice ??
        detail.purchaseAmount
    let amount = Number(amountValue)
    if (amountValue == null || isNaN(amount)) {
        amount = Number(((quantity || 0) * normalizedUnitPrice).toFixed(2))
    } else {
        amount = Number(amount.toFixed ? amount.toFixed(2) : amount)
    }

    return {
        lineId: `${detail.stockinGoodsDetailId ?? detail.detailId ?? detail.lineId ?? productId}-${Date.now()}-${Math.random()}`,
        stockinGoodsDetailId: detail.stockinGoodsDetailId ?? detail.detailId ?? detail.lineId ?? null,
        productId: productId || '',
        productName,
        productCode,
        productUnit: specification,
        specification,
        productSpecification: unit,
        unit: unit || '',
        unitGroups: buildUnitGroupsFromSingleUnit(unit),
        productTypeName: detail.productTypeName || detail.ProductTypeName || '',
        currentStock: Number(detail.currentInventory ?? detail.currentStock ?? 0),
        quantity: normalizedQuantity,
        unitPrice: normalizedUnitPrice,
        amount: amount || 0,
        remark: detail.remark || detail.memo || '',
    }
}

const unwrapDetailList = (payload: any): any[] | null => {
    if (!payload) return null
    let list = payload
    if (typeof list === 'string') {
        try {
            list = JSON.parse(list)
        } catch (err) {
            console.warn('解析明细字符串失败:', err, list)
            return null
        }
    }
    if (Array.isArray(list)) return list
    if (Array.isArray(list?.records)) return list.records
    if (Array.isArray(list?.data)) return list.data
    if (Array.isArray(list?.rows)) return list.rows
    if (Array.isArray(list?.list)) return list.list
    if (Array.isArray(list?.items)) return list.items
    if (Array.isArray(list?.Details)) return list.Details
    return null
}

const extractDetailList = (data: any): any[] => {
    const candidates = [
        data?.goodsDetails,
        data?.GoodsDetails,
        data?.stockinGoodsDetails,
        data?.StockinGoodsDetails,
        data?.stockinGoodsDetail,
        data?.StockinGoodsDetail,
        data?.details,
        data?.detail,
        data?.detailList,
        data?.DetailList,
        data?.items,
        data?.Items,
        data?.records,
        data?.Records,
        data?.data,
        data?.Data,
        data?.list,
        data?.List,
        data?.result,
        data?.Result,
        data?.stockinGoods?.goodsDetails,
        data?.stockinGoods?.stockinGoodsDetails,
        data?.stockinGoods?.detailList,
        data?.stockinGoods?.details,
        data?.baseInfo?.goodsDetails,
        data?.baseInfo?.stockinGoodsDetails,
        data?.baseInfo?.detailList,
        data?.baseInfo?.details,
    ]

    for (const candidate of candidates) {
        const list = unwrapDetailList(candidate)
        if (list && list.length) {
            return list
        }
    }
    return []
}

const requestStockinDetail = async (url: string, id: string | number) => {
    return myaxios.get(url, {
        params: { stockinGoodsId: id },
    })
}

const loadStockinGoodsDetail = async (id: string | number) => {
    if (!id) return
    detailLoading.value = true
    try {
        // 先调用新的接口（GetStockingoodsDetail），失败再回退旧接口
        let res = await requestStockinDetail('/api/StockinGoods/GetStockingoodsDetail', id).catch(
            () => null,
        )
        if (!res) {
            res = await requestStockinDetail('/api/StockinGoods/GetStockinGoodsDetail', id)
        }
        const result = res.data || {}
        if (result.code === 200) {
            const data = result.data || {}
            const baseInfo = data.stockinGoods || data.baseInfo || data
            applyStockinBaseInfo(baseInfo)
            const detailList = extractDetailList(data)
            stockinDetails.value = Array.isArray(detailList)
                ? detailList.map((item: any) => transformDetailResponse(item))
                : []
        } else {
            ElMessage.error(result.message || '获取进货详情失败')
        }
    } catch (error) {
        console.error('获取进货详情失败:', error)
        ElMessage.error('获取进货详情失败，请稍后重试')
    } finally {
        detailLoading.value = false
    }
}

const filteredOrgTree = computed(() => {
    if (!orgSearchText.value) return orgTreeData.value
    const keyword = orgSearchText.value.toLowerCase()

    const filterTree = (nodes: OrganizationItem[]): OrganizationItem[] => {
        const res: OrganizationItem[] = []
        nodes.forEach((node) => {
            const match = node.organizationName.toLowerCase().includes(keyword)
            const children = node.children ? filterTree(node.children) : []
            if (match || children.length) {
                res.push({ ...node, children })
            }
        })
        return res
    }

    return filterTree(orgTreeData.value)
})

const filteredUserList = computed(() => {
    let list = userList.value
    if (stockinForm.organizationId) {
        list = list.filter(
            (u) => u.organizationId && String(u.organizationId) === stockinForm.organizationId,
        )
    }
    if (userSearchText.value) {
        const kw = userSearchText.value.toLowerCase()
        list = list.filter((u) => u.userName.toLowerCase().includes(kw))
    }
    return list
})

const openOrgDialog = () => {
    orgDialogVisible.value = true
}

const handleSelectOrg = (node: OrganizationItem) => {
    selectedOrgNode.value = node
}

const confirmOrg = () => {
    if (!selectedOrgNode.value) {
        ElMessage.warning('请先选择部门')
        return
    }
    stockinForm.organizationId = String(selectedOrgNode.value.organizationId)
    stockinForm.organizationName = selectedOrgNode.value.organizationName
    clearUserSelection()
    orgDialogVisible.value = false
}

const openUserDialog = () => {
    if (!stockinForm.organizationName) {
        ElMessage.warning('请先选择进货部门')
        return
    }
    userDialogVisible.value = true
}

const handleSelectUser = (row: UserItem) => {
    selectedUser.value = row
}

const confirmUser = () => {
    if (!selectedUser.value) {
        ElMessage.warning('请先选择人员')
        return
    }
    stockinForm.userId = String(selectedUser.value.userId)
    stockinForm.userName = selectedUser.value.userName
    userDialogVisible.value = false
}

// 自动生成进货单号
const getStockinGoodsNo = () => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const seconds = String(now.getSeconds()).padStart(2, '0')
    const random = String(Math.floor(Math.random() * 10000)).padStart(4, '0')

    // 格式：JHD + 年月日时分秒 + 4位随机数
    // 例如：JHD202511191430250123
    stockinForm.stockinGoodsNo = `JHD${year}${month}${day}${hours}${minutes}${seconds}${random}`
}

const resetForm = () => {
    if (currentStockinGoodsId.value) {
        loadStockinGoodsDetail(currentStockinGoodsId.value)
        return
    }
    stockinForm.stockinGoodsNo = ''
    stockinForm.stockinGoodsDate = ''
    stockinForm.supplierId = ''
    stockinForm.stockinContact = ''
    stockinForm.stockinContactPhone = ''
    stockinForm.organizationId = ''
    stockinForm.organizationName = ''
    stockinForm.userId = ''
    stockinForm.userName = ''
    stockinForm.remark = ''
    stockinDetails.value = []
}

const handleSave = async () => {
    if (!isEditMode.value) {
        return
    }
    if (!stockinFormRef.value) return
    const valid = await stockinFormRef.value.validate().catch(() => false)
    if (!valid) return
    if (!stockinDetails.value.length) {
        ElMessage.warning('请至少添加一条进货明细')
        return
    }

    // 等待DOM更新完成，确保el-input-number的值已经同步
    await nextTick()
    // 再次等待，确保所有v-model绑定都已更新
    await nextTick()

    // 先同步更新所有明细的数量和单价，确保类型正确
    stockinDetails.value.forEach((item) => {
        // 处理数量
        let quantity: any = item.quantity
        if (quantity == null || quantity === undefined || quantity === '') {
            quantity = 0
        } else if (typeof quantity !== 'number') {
            quantity = Number(quantity)
            if (isNaN(quantity)) {
                quantity = 0
            }
        }
        item.quantity = quantity

        // 处理单价
        let unitPrice: any = item.unitPrice
        if (unitPrice == null || unitPrice === undefined || unitPrice === '') {
            unitPrice = 0
        } else if (typeof unitPrice !== 'number') {
            unitPrice = Number(unitPrice)
            if (isNaN(unitPrice)) {
                unitPrice = 0
            }
        }
        item.unitPrice = unitPrice

        // 重新计算金额
        if (quantity > 0 && unitPrice > 0) {
            item.amount = quantity * unitPrice
        } else {
            item.amount = 0
        }
    })

    // 再次等待，确保数据更新完成
    await nextTick()

    // 验证明细数据：检查数量和单价是否有效
    const validDetails = stockinDetails.value.filter((item) => {
        // 获取数量值（已经在上面的循环中转换为数字）
        const quantity = Number(item.quantity)

        // 验证数量是否有效且大于0
        if (isNaN(quantity) || !isFinite(quantity) || quantity <= 0) {
            return false
        }

        // 获取单价值（已经在上面的循环中转换为数字）
        const unitPrice = Number(item.unitPrice)

        // 验证单价是否有效且大于0
        if (isNaN(unitPrice) || !isFinite(unitPrice) || unitPrice <= 0) {
            return false
        }

        return true
    })

    if (validDetails.length === 0) {
        // 调试信息：输出详细的验证失败原因
        const debugInfo = stockinDetails.value.map((item, index) => {
            const qty: any = item.quantity
            const price: any = item.unitPrice
            const qtyNum = Number(qty)
            const priceNum = Number(price)

            return {
                序号: index + 1,
                货品名称: item.productName,
                货品编号: item.productCode,
                数量: {
                    原始值: qty,
                    类型: typeof qty,
                    转换为数字: qtyNum,
                    是否NaN: isNaN(qtyNum),
                    是否有限: isFinite(qtyNum),
                    是否大于0: qtyNum > 0,
                    是否为空: qty == null || qty === undefined || qty === '',
                },
                单价: {
                    原始值: price,
                    类型: typeof price,
                    转换为数字: priceNum,
                    是否NaN: isNaN(priceNum),
                    是否有限: isFinite(priceNum),
                    是否大于0: priceNum > 0,
                    是否为空: price == null || price === undefined || price === '',
                },
                验证结果: !isNaN(qtyNum) && isFinite(qtyNum) && qtyNum > 0 &&
                    !isNaN(priceNum) && isFinite(priceNum) && priceNum > 0,
            }
        })
        console.error('验证失败 - 明细数据详情:', debugInfo)
        console.error('验证失败 - 原始明细数据:', stockinDetails.value)

        // 找出哪些明细缺少数量或单价
        const missingFields = stockinDetails.value.map((item, index) => {
            const qty: any = item.quantity
            const price: any = item.unitPrice
            const qtyNum = Number(qty)
            const priceNum = Number(price)
            const issues: string[] = []

            if (qty == null || qty === undefined || qty === '') {
                issues.push('缺少进货数量')
            } else if (isNaN(qtyNum) || !isFinite(qtyNum)) {
                issues.push(`进货数量无效(${qty})`)
            } else if (qtyNum <= 0) {
                issues.push(`进货数量必须大于0(当前:${qtyNum})`)
            }

            if (price == null || price === undefined || price === '') {
                issues.push('缺少进货单价')
            } else if (isNaN(priceNum) || !isFinite(priceNum)) {
                issues.push(`进货单价无效(${price})`)
            } else if (priceNum <= 0) {
                issues.push(`进货单价必须大于0(当前:${priceNum})`)
            }

            return {
                index: index + 1,
                productName: item.productName,
                productCode: item.productCode,
                issues
            }
        }).filter(item => item.issues.length > 0)

        if (missingFields.length > 0) {
            console.error('缺少必填字段的明细:', missingFields)
            const productNames = missingFields.map(f => `${f.productName}(${f.issues.join('，')})`).join('、')
            ElMessage.warning(`以下货品的进货明细不完整：${productNames}`)
        } else {
            console.error('未找到缺失字段，但验证仍然失败，请检查控制台调试信息')
            ElMessage.warning('进货明细不能为空，请至少填写一条有效的明细（进货数量和进货单价必须大于0）')
        }
        return
    }

    if (validDetails.length < stockinDetails.value.length) {
        ElMessage.warning(`已过滤 ${stockinDetails.value.length - validDetails.length} 条无效明细（数量或单价为0），仅保存有效明细`)
    }

    // 构建明细数据，确保所有字段都正确映射到后端期望的字段名
    // 根据Swagger文档，后端期望的字段名：
    // - goodsDetails (不是 stockinGoodsDetails)
    // - purchasePrice (不是 unitPrice)
    // - specificationModel (不是 productSpecification)
    // - unitName (不是 productUnit)
    // - currentInventory (不是 currentStock)
    const detailPayload = validDetails.map((item:any, index) => {
        // 规格字段（对应货品表的productUnit）
        const specification = item.productUnit || item.specification || ''
        // 单位字段（对应货品表的productspecification，但实际使用单位是unit）
        const unit = item.unit || item.productSpecification || ''
        const baseInventory = Number(item.currentStock ?? item.currentInventory ?? 0)
        // 确保数量和单价是有效的数字
        const quantity = Number(item.quantity)
        const unitPrice = Number(item.unitPrice)
        const amount = quantity * unitPrice
        const updatedInventory = quantity > 0 ? baseInventory + quantity : baseInventory

        // 验证关键字段
        if (!item.productId || quantity <= 0 || unitPrice <= 0) {
            console.warn('明细数据验证失败:', {
                productId: item.productId,
                quantity,
                unitPrice,
                productName: item.productName
            })
        }

        const detailId = item.stockinGoodsDetailId ?? null
        return {
            // 后端期望的字段名
            productId: Number(item.productId),                    // 必须转换为数字
            productCode: String(item.productCode || ''),           // 货品编号
            productName: String(item.productName || ''),           // 货品名称
            specificationModel: String(specification || ''),       // 规格型号（后端期望的字段名，需为字符串）
            unitName: String(unit || ''),                          // 单位（后端期望的字段名，需为字符串）
            productTypeName: String(item.productTypeName || ''),   // 货品类型
            currentInventory: Number(updatedInventory),           // 当前库存（原库存 + 新增数量）
            quantity: quantity,                                   // 进货数量
            purchasePrice: unitPrice,                             // 进货单价（后端期望的字段名，不是unitPrice）
            amount: Number(amount.toFixed(2)),                    // 进货金额
            remark: String(item.remark || ''),                     // 备注
            stockinGoodsDetailId: detailId,
            detailId,
        }
    })

    // 验证明细数据是否为空
    if (!detailPayload || detailPayload.length === 0) {
        console.error('明细数据为空，无法保存')
        ElMessage.error('进货明细不能为空，请至少添加一条有效的明细')
        return
    }

    // 计算有效明细的统计信息
    const validTotalQuantity = validDetails.reduce((sum, item) => sum + Number(item.quantity ?? 0), 0)
    const validTotalAmount = validDetails.reduce((sum, item) => sum + Number(item.amount ?? 0), 0)

    // ========================================
    // 构建保存数据，同时包含基础信息和明细信息
    // 根据Swagger文档，后端期望的数据结构：
    // {
    //   stockinTime: string (ISO格式日期时间),
    //   stockinRemark: string,
    //   creator: string,
    //   goodsDetails: array (不是 stockinGoodsDetails)
    // }
    // ========================================

    // 构建基础信息（保留原始字段，便于后端兼容）
    const baseInfo = {
        stockinGoodsNo: stockinForm.stockinGoodsNo,           // 进货单号
        stockinGoodsDate: stockinForm.stockinGoodsDate,       // 进货日期
        supplierId: stockinForm.supplierId,                   // 供应商ID
        stockinContact: stockinForm.stockinContact,           // 联系人
        stockinContactPhone: stockinForm.stockinContactPhone, // 联系方式
        organizationId: stockinForm.organizationId,           // 部门ID
        organizationName: stockinForm.organizationName,       // 部门名称
        userId: stockinForm.userId,                           // 用户ID
        userName: stockinForm.userName,                       // 用户名称
        stockinUser: stockinForm.userName,                    // 进货人
        stockinDepartment: stockinForm.organizationName,      // 进货部门
        remark: stockinForm.remark,                           // 备注
        stockinGoodsCount: Number(validTotalQuantity),             // 总数量
        stockinGoodsAmount: Number(validTotalAmount.toFixed(2)),   // 总金额
        createor: stockinForm.userName,                       // 创建人
        createrTime: new Date().toISOString(),                // 创建时间
    }

    // 构建符合后端期望的payload
    // 根据后端验证错误，后端需要以下必填字段：
    // - StockinUser (进货人) - 必填
    // - StockinDepartment (进货部门) - 必填
    // - goodsDetails (进货明细数组) - 必填
    const payload: any = {
        // Swagger文档中的基础字段
        stockinTime: stockinForm.stockinGoodsDate
            ? new Date(stockinForm.stockinGoodsDate).toISOString()
            : new Date().toISOString(),                        // 进货时间（ISO格式）
        stockinRemark: stockinForm.remark || '',             // 备注
        creator: stockinForm.userName || '',                  // 创建人

        // 后端验证需要的必填字段（根据400错误添加）
        StockinUser: stockinForm.userName || '',              // 进货人（后端必填字段）
        StockinDepartment: stockinForm.organizationName || '', // 进货部门（后端必填字段）

        // 明细信息（使用后端期望的字段名 goodsDetails）
        goodsDetails: detailPayload,                           // 进货明细数组（后端期望的字段名）
        // 保留原有基础字段，确保兼容
        ...baseInfo,
    }

    // 验证必填字段
    if (!payload.StockinUser) {
        ElMessage.error('请选择进货人')
        return
    }
    if (!payload.StockinDepartment) {
        ElMessage.error('请选择进货部门')
        return
    }

    // 输出调试信息，方便查看发送到后端的数据
    console.log('保存进货单 - 请求数据（基础信息 + 明细信息）:', {
        明细数量: detailPayload.length,
        明细数据: detailPayload.map(d => ({
            productId: `${d.productId} (${typeof d.productId})`,
            productName: d.productName,
            productCode: d.productCode,
            quantity: `${d.quantity} (${typeof d.quantity})`,
            purchasePrice: `${d.purchasePrice} (${typeof d.purchasePrice})`,
            amount: `${d.amount} (${typeof d.amount})`,
            specificationModel: d.specificationModel,
            unitName: d.unitName,
        })),
        完整payload: JSON.parse(JSON.stringify(payload))
    })

    // 再次验证明细数据（使用正确的字段名 goodsDetails）
    if (!payload.goodsDetails || payload.goodsDetails.length === 0) {
        console.error('Payload中的明细数据为空')
        ElMessage.error('进货明细不能为空，请至少添加一条有效的明细')
        return
    }

    // 验证每条明细的关键字段
    const invalidDetails = payload.goodsDetails.filter((d: any) => {
        return !d.productId ||
            !d.quantity || d.quantity <= 0 ||
            !d.purchasePrice || d.purchasePrice <= 0
    })

    if (invalidDetails.length > 0) {
        console.error('存在无效的明细数据:', invalidDetails)
        ElMessage.error('进货明细数据不完整，请确保所有明细的进货数量和进货单价都已填写且大于0')
        return
    }

    if (!currentStockinGoodsId.value) {
        ElMessage.error('缺少进货单ID，无法保存')
        return
    }

    saving.value = true
    try {
        payload.stockinGoodsId = currentStockinGoodsId.value
        const res = await myaxios.put('/api/StockinGoods/UpdateStockinGoods', payload)
        const result = res.data || {}
        if (result.code === 200) {
            ElMessage.success(result.message || '进货单修改成功')
            router.push('/GetStockingGoods')
        } else {
            // 后端返回的错误消息
            const errorMsg = result.message || '修改失败，请检查数据是否正确'
            console.error('后端返回错误:', result)

            // 如果后端返回"进货明细不能为空"等错误，显示更详细的提示
            if (errorMsg.includes('明细') || errorMsg.includes('不能为空')) {
                ElMessage.error(`${errorMsg}。请确保所有明细的进货数量和进货单价都已填写且大于0`)
            } else {
                ElMessage.error(errorMsg)
            }
        }
    } catch (error: any) {
        console.error('保存进货单失败:', error)
        console.error('错误详情:', {
            message: error?.message,
            response: error?.response?.data,
            status: error?.response?.status,
        })

        // 获取错误消息
        let errorMessage = '修改失败，请稍后重试'
        const errorData = error?.response?.data

        // 处理400验证错误
        if (error?.response?.status === 400 && errorData?.errors) {
            const validationErrors: string[] = []
            Object.keys(errorData.errors).forEach((field) => {
                const fieldErrors = errorData.errors[field]
                if (Array.isArray(fieldErrors)) {
                    fieldErrors.forEach((msg: string) => {
                        validationErrors.push(msg)
                    })
                }
            })

            if (validationErrors.length > 0) {
                errorMessage = validationErrors.join('；')
                console.error('验证错误详情:', errorData.errors)
            } else {
                errorMessage = errorData.title || errorData.message || errorMessage
            }
        } else if (errorData) {
            errorMessage = errorData.message || errorData.error || errorData.title || errorMessage
        } else if (error?.message) {
            errorMessage = error.message
        }

        // 显示错误消息
        if (errorMessage.includes('明细') || errorMessage.includes('不能为空')) {
            ElMessage.error(`${errorMessage}。请确保所有明细的进货数量和进货单价都已填写且大于0`)
        } else if (errorMessage.includes('StockinUser') || errorMessage.includes('进货人')) {
            ElMessage.error('请选择进货人')
        } else if (errorMessage.includes('StockinDepartment') || errorMessage.includes('进货部门')) {
            ElMessage.error('请选择进货部门')
        } else {
            ElMessage.error(errorMessage)
        }
    } finally {
        saving.value = false
    }
}

const goBack = () => {
    router.push('/GetStockingGoods')
}

const gotoCreateSupplier = () => {
    router.push('/CreateSupplier')
}

const clearOrgSelection = () => {
    stockinForm.organizationId = ''
    stockinForm.organizationName = ''
    selectedOrgNode.value = null
    clearUserSelection()
}

const clearUserSelection = () => {
    stockinForm.userId = ''
    stockinForm.userName = ''
    selectedUser.value = null
}

const handleDetailSelectionChange = (rows: StockinDetailItem[]) => {
    selectedDetailRows.value = rows
}

const removeDetail = (index: number) => {
    stockinDetails.value.splice(index, 1)
}

const removeSelectedDetails = () => {
    if (!selectedDetailRows.value.length) {
        ElMessage.warning('请选择需要移除的明细')
        return
    }
    stockinDetails.value = stockinDetails.value.filter(
        (item) => !selectedDetailRows.value.includes(item),
    )
    selectedDetailRows.value = []
    ElMessage.success('已移除选中的明细')
}

const updateDetailAmount = (row: StockinDetailItem) => {
    // 确保数量和单价是正确的数字类型
    let quantity: number = 0
    if (row.quantity != null && row.quantity !== undefined) {
        quantity = typeof row.quantity === 'number' ? row.quantity : Number(row.quantity) || 0
        if (isNaN(quantity) || !isFinite(quantity)) {
            quantity = 0
        }
    }

    let unitPrice: number = 0
    if (row.unitPrice != null && row.unitPrice !== undefined) {
        unitPrice = typeof row.unitPrice === 'number' ? row.unitPrice : Number(row.unitPrice) || 0
        if (isNaN(unitPrice) || !isFinite(unitPrice)) {
            unitPrice = 0
        }
    }

    // 计算金额，保留2位小数
    row.amount = Number((quantity * unitPrice).toFixed(2))

    // 如果金额无效，设置为0
    if (isNaN(row.amount) || !isFinite(row.amount)) {
        row.amount = 0
    }
}

const handleUnitChange = (row: StockinDetailItem) => {
    // 单位变化时，更新 productSpecification 字段以保持数据一致性
    if (row.unit) {
        row.productSpecification = row.unit
    }
    // 预留处理单位换算的逻辑
    // 例如：如果切换到不同的单位，可能需要重新计算数量或单价
}

const totalProductKinds = computed(() => stockinDetails.value.length)
const totalProductQuantity = computed(() =>
    stockinDetails.value.reduce((sum, item) => sum + (item.quantity || 0), 0),
)
const totalProductAmount = computed(() =>
    stockinDetails.value.reduce((sum, item) => sum + (item.amount || 0), 0),
)

const openProductDialog = () => {
    productDialogVisible.value = true
    selectedProducts.value = []
    if (!productList.value.length) {
        searchProducts()
    }
}

const buildUnitGroupsFromProduct = (product: ProductListItem): UnitOptionGroup[] => {
    const groups: UnitOptionGroup[] = []
    const mainUnits: UnitOption[] = []
    const assistUnits: UnitOption[] = []

    const normalizeUnit = (unitValue: any) => {
        if (!unitValue) return ''
        if (typeof unitValue === 'string') return unitValue
        if (typeof unitValue === 'object') {
            return (
                unitValue.unitName ||
                unitValue.unit ||
                unitValue.label ||
                unitValue.name ||
                ''
            )
        }
        return String(unitValue)
    }

    const mainUnitName = normalizeUnit(
        product.productUnit || product.mainUnit || product.mainUnitName || product.unitDisplay,
    )
    if (mainUnitName) {
        mainUnits.push({
            label: mainUnitName,
            value: mainUnitName,
            description: '主单位',
        })
    }

    const rawUnits =
        product.auxiliaryUnits ||
        product.assistUnits ||
        product.unitOptions ||
        product.unitList ||
        product.units ||
        []

    const candidates = Array.isArray(rawUnits) ? rawUnits : [rawUnits]
    candidates.forEach((unit: any, index: number) => {
        if (!unit) return
        const label = normalizeUnit(unit)
        if (!label) return
        const convertQty =
            unit.convertQty ||
            unit.convertQuantity ||
            unit.rate ||
            (unit.conversion && unit.conversion.rate) ||
            null
        const desc =
            unit.description ||
            unit.convertText ||
            unit.convertDesc ||
            (convertQty && mainUnitName ? `= ${convertQty} ${mainUnitName}` : '') ||
            ''
        assistUnits.push({
            label,
            value: label,
            description: desc || `辅助单位${assistUnits.length + 1}`,
        })
    })

    if (mainUnits.length) {
        groups.push({ label: '主单位', options: mainUnits })
    }
    if (assistUnits.length) {
        groups.push({ label: '辅助单位', options: assistUnits })
    }
    return groups.length ? groups : [{ label: '主单位', options: [{ label: mainUnitName || '主单位', value: mainUnitName || '' }] }]
}

const normalizeProductRecord = (record: any): ProductListItem | null => {
    const productId =
        record.productId ??
        record.productID ??
        record.id ??
        record.productid ??
        record.ProductId ??
        null
    if (!productId) return null

    // 根据货品表的映射：
    // productUnit 是规格
    // productspecification 是单位
    const specification = record.productUnit ?? record.mainUnit ?? record.mainUnitName ?? record.unit ?? ''
    const unit = record.productspecification ?? record.productSpecification ?? record.specification ?? record.specificationModel ?? record.spec ?? ''

    const productName = record.productName ?? record.name ?? ''
    const productCode = record.productCode ?? record.code ?? ''

    return {
        ...record,
        productId,
        productName,
        productCode,
        producttypeName: record.producttypeName ?? record.productTypeName ?? record.typeName,
        // 规格字段映射
        productUnit: specification,
        mainUnit: specification,
        unitDisplay: specification,
        // 单位字段映射
        productspecification: unit,
        productSpecification: unit,
        specification: unit,
        // 其他字段
        inventoryCurrtnumber:
            record.inventoryCurrtnumber ?? record.currentInventory ?? record.stock ?? 0,
        productInmoney: record.productInmoney ?? record.inPrice ?? record.purchasePrice ?? 0,
    }
}

const buildProductKey = (item: ProductListItem) =>
    `${item.productId ?? ''}__${item.productCode ?? ''}__${item.specification ?? ''}`

const normalizeProductList = (list: any[]): ProductListItem[] => {
    const map = new Map<string, ProductListItem>()
    list.forEach((item) => {
        const normalized = normalizeProductRecord(item)
        if (!normalized) return
        const key = buildProductKey(normalized)
        if (!map.has(key)) {
            map.set(key, normalized)
        }
    })
    return Array.from(map.values())
}

const enrichProductUnits = (list: ProductListItem[]) => {
    const dynamicUnits = new Set<string>()
    list.forEach((item) => {
        const unit =
            item.productUnit ||
            item.mainUnit ||
            item.mainUnitName ||
            item.unitDisplay ||
            ''
        if (unit) {
            dynamicUnits.add(unit)
            item.unitDisplay = unit
        }
    })
    const orderedUnits: string[] = []
    DEFAULT_UNIT_OPTIONS.forEach((unit) => {
        orderedUnits.push(unit)
    })
    dynamicUnits.forEach((unit) => {
        if (!orderedUnits.includes(unit)) {
            orderedUnits.push(unit)
        }
    })
    productUnitOptions.value = orderedUnits
}

const searchProducts = async () => {
    productTableLoading.value = true
    try {
        const res = await myaxios.get('/api/Product/GetProduct', {
            params: {
                Pageindex: productPagination.pageindex,
                PageSize: productPagination.pagesize,
                ProductName: productSearchForm.keyword,
                ProductUnit: productSearchForm.unit,
                number: 1,
            },
        })
        if (res.data.code === 200) {
            const rawList = res.data.data?.data || []
            const normalizedList = normalizeProductList(rawList)
            productList.value = normalizedList
            productPagination.total = res.data.data?.listCount || 0
            enrichProductUnits(productList.value)
        } else {
            ElMessage.error(res.data.message || '获取货品失败')
        }
    } catch (error) {
        console.error('获取货品失败:', error)
        ElMessage.error('获取货品失败')
    } finally {
        productTableLoading.value = false
    }
}

const resetProductSearch = () => {
    productSearchForm.keyword = ''
    productSearchForm.unit = ''
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductSelectionChange = (rows: ProductListItem[]) => {
    selectedProducts.value = rows
}

const handleProductSizeChange = (size: number) => {
    productPagination.pagesize = size
    productPagination.pageindex = 1
    searchProducts()
}

const handleProductCurrentChange = (page: number) => {
    productPagination.pageindex = page
    searchProducts()
}

const transformProductToDetail = (product: ProductListItem): StockinDetailItem => {
    const unitGroups = buildUnitGroupsFromProduct(product)

    // 根据货品表映射：
    // productUnit是规格
    // productspecification是单位
    const specification = product.productUnit || product.mainUnit || product.unitDisplay || ''
    const unit = product.productspecification || product.productSpecification || product.specification || ''

    // 默认单位优先使用货品的单位，如果没有则使用单位组中的第一个
    const defaultUnit =
        unit ||
        unitGroups[0]?.options[0]?.value ||
        ''

    return {
        lineId: `${product.productId}-${Date.now()}`,
        productId: product.productId,
        productName: product.productName,
        productCode: product.productCode,
        // 规格字段（对应货品表的productUnit）
        productUnit: specification,
        specification: specification,
        // 单位字段（对应货品表的productspecification）
        productSpecification: unit,
        unit: defaultUnit,
        unitGroups,
        productTypeName: product.producttypeName,
        currentStock: product.inventoryCurrtnumber || 0,
        // 初始值：quantity设置为null，unitPrice设置为产品的入库单价
        // el-input-number组件在使用null作为初始值时，用户必须输入才能继续
        quantity: null as any, // el-input-number会在用户输入后自动更新为数字类型
        unitPrice: product.productInmoney || 0,
        amount: 0,
        remark: '',
    }
}

const confirmProductSelection = () => {
    if (!selectedProducts.value.length) {
        ElMessage.warning('请选择需要添加的货品')
        return
    }
    let added = 0
    let skipped = 0
    selectedProducts.value.forEach((item) => {
        if (stockinDetails.value.find((detail) => detail.productId === item.productId)) {
            skipped++
            return
        }
        stockinDetails.value.push(transformProductToDetail(item))
        added++
    })
    productDialogVisible.value = false
    selectedProducts.value = []
    if (added) {
        ElMessage.success(`成功添加 ${added} 个货品${skipped ? `，跳过 ${skipped} 个重复货品` : ''}`)
    } else {
        ElMessage.warning('所选货品已全部存在')
    }
}

onMounted(async () => {
    const stockinGoodsId = normalizeStockinGoodsId(
        route.query.stockinGoodsId ?? route.params.stockinGoodsId ?? null,
    )
    if (!stockinGoodsId) {
        ElMessage.error('缺少进货单ID')
        router.push('/GetStockingGoods')
        return
    }
    currentStockinGoodsId.value = stockinGoodsId
    if (isEditMode.value) {
        preloadBaseInfoFromCache()
    }

    const baseTasks = [
        loadSuppliers(),
        loadOrganizations(),
        loadUsers(),
        loadUnitOptions(),
    ]

    await Promise.allSettled([
        ...baseTasks,
        loadStockinGoodsDetail(stockinGoodsId),
    ])

    if (isEditMode.value) {
        sessionStorage.removeItem(STOCKIN_EDIT_CACHE_KEY)
    }
})
</script>

<style scoped>
.common-layout {
    padding: 20px;
    position: relative;
}

.card-block {
    margin-bottom: 16px;
}

.card-title {
    font-weight: bold;
}

.inline-input {
    display: flex;
    align-items: center;
    gap: 8px;
}

.link-btn {
    padding: 0 4px;
}

.detail-placeholder {
    padding: 16px;
    color: #909399;
    font-size: 13px;
}

.detail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.detail-actions {
    display: flex;
    gap: 12px;
}

.detail-summary {
    margin-top: 16px;
    padding: 12px 16px;
    background: #f5f7fa;
    border-radius: 4px;
    display: flex;
    gap: 24px;
    color: #606266;
}

.product-search-form {
    margin-bottom: 16px;
}

.product-pagination {
    margin-top: 16px;
    text-align: right;
}

.unit-desc {
    color: #909399;
    margin-left: 6px;
    font-size: 12px;
}

.dialog-search {
    margin-bottom: 12px;
}

.fixed-footer {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: #fff;
    border-top: 1px solid #e4e7ed;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;
}

.footer-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 12px 20px;
    display: flex;
    justify-content: flex-end;
    gap: 12px;
}
</style>